package ynu.edu.entity;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Getter;
import lombok.Setter;
import org.aspectj.weaver.ast.Or;

import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

@Entity
@Getter
@Setter
@DiscriminatorValue(User.TYPE_CUSTOMER)
@JsonIgnoreProperties(value = {"hibernateLazyInitializer", "handler", "fieldHandler"})
public class Customer extends User {
    @OneToMany(cascade = CascadeType.ALL,fetch = FetchType.EAGER,orphanRemoval = true)
    @JoinColumn(name = "customer_id")
    @JsonIgnoreProperties("customer")
    private Set<Order> orders;

    @JsonIgnore
    public Order getUnpaidOrderByShop(Shop shop){
        return getOrders().stream().filter(o ->
                Objects.equals(o.getOrderState(), Order.ORDER_STATE_UNPAID)
                        && Objects.equals(o.getShop().getId(), shop.getId())
                        && Objects.equals(o.getIsDeleted(),0)
        ).findFirst().orElse(null);
    }

    @JsonIgnore
    public Customer placeOrder(Order order){
        this.orders.add(order);
        order.setCustomer(this);
        return this;
    }

    @JsonIgnore
    public Order payOrder(Order order){
        if (orders.contains(order)){
            order.setOrderState(Order.ORDER_STATE_PAID);
            return order;
        }
        return null;
    }

    @JsonIgnore
    public Order cancelOrder(Order order){
        if (orders.contains(order) &&
                Objects.equals(order.getOrderState(), Order.ORDER_STATE_UNPAID) &&
                order.getIsDeleted() == 0){
            //逻辑删除
            order.setIsDeleted(1);
            return order;
        }
        return null;
    }

//    @JsonIgnore
//    public List<Order> getMyOrders(){
//        return new ArrayList<>(this.getOrders());
//    }
}

